package com.agileboot.common.utils.bean;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * Bean属性复制工具类
 * 
 * @author ruoyi
 */
public class BeanCopyUtils {
    /**
     * 复制对象
     *
     * @param source 源对象
     * @param targetClass 目标对象类型
     * @return 目标对象
     */
    public static <T> T copy(Object source, Class<T> targetClass) {
        if (source == null) {
            return null;
        }
        
        try {
            T target = targetClass.newInstance();
            BeanUtil.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            throw new RuntimeException("Bean copy error: " + e.getMessage(), e);
        }
    }

    /**
     * 复制对象
     *
     * @param source 源对象
     * @param targetSupplier 目标对象供应方
     * @return 目标对象
     */
    public static <T> T copy(Object source, Supplier<T> targetSupplier) {
        if (source == null) {
            return null;
        }
        
        T target = targetSupplier.get();
        BeanUtil.copyProperties(source, target);
        return target;
    }

    /**
     * 复制对象列表
     *
     * @param sourceList 源对象列表
     * @param targetClass 目标对象类型
     * @return 目标对象列表
     */
    public static <T, S> List<T> copyList(List<S> sourceList, Class<T> targetClass) {
        if (sourceList == null || sourceList.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<T> targetList = new ArrayList<>(sourceList.size());
        for (S source : sourceList) {
            targetList.add(copy(source, targetClass));
        }
        return targetList;
    }

    /**
     * 复制对象列表
     *
     * @param sourceList 源对象列表
     * @param targetSupplier 目标对象供应方
     * @return 目标对象列表
     */
    public static <T, S> List<T> copyList(List<S> sourceList, Supplier<T> targetSupplier) {
        if (sourceList == null || sourceList.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<T> targetList = new ArrayList<>(sourceList.size());
        for (S source : sourceList) {
            T target = targetSupplier.get();
            BeanUtil.copyProperties(source, target);
            targetList.add(target);
        }
        return targetList;
    }
} 